<template>
  <div class="vue-editor">
    <div ref="editor"></div>
  </div>
</template>
<script>
import E from 'wangeditor';

export default {
  props: {
    content: String,
    value: String,
    menus: Array
  },
  data() {
    return {
      editor: null,
      innerContent: '',
      defaultMenus: [
        'head', // 标题
        'bold', // 粗体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'list', // 列表
        'justify', // 对齐方式
        'quote', // 引用
        'image', // 插入图片
        'table', // 表格
        'undo', // 撤销
        'redo' // 重复
      ]
    };
  },
  watch: {
    'content'(newVal) {
      if (this.editor) {
        if (!!newVal && newVal !== this.innerContent) {
          this.innerContent = newVal;
          this.editor.txt.html(newVal);
        } else if (!newVal) {
          this.editor.txt.clear();
        }
      }
    },
    'value'(newVal) {
      if (this.editor) {
        if (!!newVal && newVal !== this.innerContent) {
          this.innerContent = newVal;
          this.editor.txt.html(newVal);
        } else if (!newVal) {
          this.editor.txt.clear();
        }
      }
    }
  },
  methods: {
    initialize() {
      if (this.$el) {
        this.editor = new E(this.$refs.editor);
        console.log(this.editor)
        // if (this.menus && this.menus.length > 0) {
        //   this.editor.config.menus = this.menus;
        // } else {
        //   this.editor.config.menus = this.defaultMenus;
        // }
        this.editor.config.zIndex = 100;
        this.editor.config.uploadImgShowBase64 = true;
        this.editor.config.onchange = (html) => {
          const text = this.editor.txt.text();
          this.innerContent = html;
          this.$emit('input', this.innerContent);
          this.$emit('change', {
            editor: this.editor,
            html: html,
            text: text
          });
        };

        this.editor.create();

        if (this.value || this.content) {
          this.editor.txt.html(this.value || this.content);
        }

        this.$emit('ready', this.editor);
      }
    }
  },
  mounted() {
    this.initialize();
  },
  beforeDestroy() {
    this.editor = null;
  }
};
</script>
<style scoped>
.vue-editor img {
  max-width: 100%;
}
</style>